<template>
  <div id="map_container">
    <div class="changeMap">
      <el-tooltip
        class="item"
        effect="dark"
        content="点击切换为二维地图"
        placement="left"
      >
        <img
          src="../assets/nav-img/2dearth.svg"
          alt=""
          class="change1"
          @click="add()"
        />
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="点击切换为卫星地图"
        placement="left"
      >
        <img
          src="../assets/nav-img/3dearth.jpg"
          alt=""
          class="change2"
          @click="remove()"
        />
      </el-tooltip>
    </div>
    <!-- ************************目录树************************* -->
    <!-- 视频监控popup弹窗 -->
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
/* 视频监控弹窗图层 */
var drawSource = new ol.source.Vector({
  wrapX: false,
});
var drawLayer = new ol.layer.Vector({
  source: drawSource,
  style: new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 150],
      anchorOrigin: 'top-right',
      anchorXUnits: 'fraction',
      anchorYUnits: 'pixels',
      offsetOrigin: 'top-right',
      // offset:[0,10],
      //图标缩放比例
      scale: 0.08,
      //透明度
      opacity: 1,
      //图标的url
      src: '../../img/monitor.png',
    }),
  }),
});
export default {
  components: {},
  data() {
    return {};
  },
  computed: {
    ...mapState(['highLightCamera', 'map']),
  },
  watch: {
    highLightCamera: function (n, o) {
      console.log('变化了');
      if (this.highLightCamera == true) {
        this.highLight();
      } else {
        console.log('关闭');
        this.map.removeLayer(drawLayer);
      }
    },
    deep: true,
  },
  mounted() {
    this.initmap();
    var that = this;
    /* -------------------------------------------
                        地图文档操作
      -------------------------------------------- */
    var docName = 'guanggu';
    var docLayer = new Zondy.Map.Doc('', docName, {
      ip: 'localhost',
      port: 6163,
    });
    console.log(docLayer);
    var map = new ol.Map({
      //设置地图容器挂载到对应的DOM节点
      target: 'map_container',
      layers: [tiandituYX, tianditu, docLayer, tiandituZJ],
      //设置地图以什么样的方式显示
      view: new ol.View({
        center: [114.37, 30.5],
        projection: 'EPSG:4326',
        zoom: 13,
      }),
    });
    this.$store.commit('addMap', map);
    this.$store.commit('addLayer', docLayer);
    // map.addLayer(tianditu);
    // var key = "0526d527ee9f5775642bdc1251354620";

    /* -------------------------------------------
                         鹰眼控件
      -------------------------------------------- */
    const overviewMapControl = new ol.control.OverviewMap({
      /* 鹰眼控件样式  */
      className: 'ol-overviewmap ol-custom-overviewmap',
      layers: [gaode],
      /* 鹰眼控件展开时功能按钮上的标识(网页的JS的字符编码) */
      collapseLabel: '\u00BB',
      /* 鹰眼控件折叠时功能按钮上的标识(网页的JS的字符编码) */
      label: '\u00AB',
      /* 初始为展开显示方式 */
      collapsed: false,
      view: new ol.View({
        projection: 'EPSG:4326',
        minZoom: 6,
      }),
    });
    map.addControl(overviewMapControl);
    /* -------------------------------------------
                        比例尺
      -------------------------------------------- */
    const scaleLineControl = new ol.control.ScaleLine({
      /* 设置比例尺单位,degrees,imperial,us,nautical,metric */
      units: 'metric',
    });
    map.addControl(scaleLineControl);
    /* -------------------------------------------
                        视图跳转控件
      -------------------------------------------- */
    const ZoomToExtend = new ol.control.ZoomToExtent({
      extent: [114.377, 30.45, 114.38, 30.54],
    });
    map.addControl(ZoomToExtend);
  },

  methods: {
    initmap() {},
    add() {
      tianditu.setVisible(true);
    },
    remove() {
      tianditu.setVisible(false);
    },
    highLight() {
      /* 1. 高亮显示所有摄像头点 */
      //创建一个用于查询的点形状
      let pointObj = new Zondy.Object.Point2D(114, 30);
      //设置查询点的搜索半径 (度)
      pointObj.nearDis = 2;

      // 查询
      var queryStruct = new Zondy.Service.QueryFeatureStruct();
      //是否包含几何图形信息
      queryStruct.IncludeGeometry = true;
      //是否包含属性信息
      queryStruct.IncludeAttribute = true;
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic = false;
      //指定查询规则
      var rule = new Zondy.Service.QueryFeatureRule({
        //是否将要素的可见性计算在内
        EnableDisplayCondition: false,
        //是否完全包含
        MustInside: false,
        //是否仅比较要素的外包矩形
        CompareRectOnly: false,
        //是否相交
        Intersect: true,
      });
      //实例化查询参数对象
      var queryParam = new Zondy.Service.QueryParameter({
        geometry: pointObj,
        resultFormat: 'json',
        struct: queryStruct,
        rule: rule,
      });
      var queryService = new Zondy.Service.QueryDocFeature(
        queryParam,
        'guanggu',
        '2',
        {
          ip: 'localhost',
          port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089
        }
      );

      //执行查询操作，querySuccess为查询回调函数
      queryService.query(querySuccess, queryError);

      //查询失败回调
      function queryError(e) {
        //停止进度条
        console.log('失败', e);
      }

      // 下面的函数会改变this指向, 所以这里接收一下现在的this, 方便后面使用
      var _this = this;
      var new_flag = this.highLightCamera;
      // var new_flag = true

      // console.log('new', new_flag);
      //查询成功回调
      function querySuccess(result) {
        console.log('查询成功', result);
        if (new_flag) {
          // console.log('显示摄像头成功', result);
          var format = new Zondy.Format.PolygonJSON();
          //将MapGIS要素JSON反序列化为ol.Feature类型数组
          var features = format.read(result);
          drawSource.addFeatures(features);
          _this.map.addLayer(drawLayer);

          _this.map.setView(
            new ol.View({
              projection: 'EPSG:4326',
              center: [114.37, 30.5],
              zoom: 13,
            })
          );

          /* 2. 点击显示pop弹窗 */
          // console.log('执行中');
          /* 设置点要素 */
          // 二. 将dom转换成overlay
          var container = document.getElementById('popup');
          var content = document.getElementById('popup-content');
          var closer = document.getElementById('popup-closer');
          const popup = new ol.Overlay({
            //要转换成overlay的HTML元素
            element: container,
            //当前窗口可见
            autoPan: true,
            //Popup放置的位置
            positioning: 'bottom-center',
            //是否应该停止事件传播到地图窗口
            stopEvent: false,
            autoPanAnimation: {
              //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
              duration: 250,
            },
          });
          _this.map.addOverlay(popup);

          //添加关闭按钮的单击事件（隐藏popup）
          closer.onclick = function () {
            //未定义popup位置
            popup.setPosition(undefined);
            //失去焦点
            closer.blur();
            return false;
          };

          /**
           * 动态创建popup的具体内容
           * @param {string} title
           */
          function addFeatrueInfo(info) {
            //新增a元素
            var elementA = document.createElement('a');
            elementA.className = 'class_a';
            elementA.href = '#';
            //elementA.innerText = info.att.title;
            setInnerText(elementA, info.att.title);
            // 新建的div元素添加a子节点
            content.appendChild(elementA);
            //新增p元素
            var elementDiv = document.createElement('p');
            elementDiv.className = 'class_text';
            //elementDiv.innerText = info.att.text;
            setInnerText(elementDiv, info.att.text);
            // 为content添加div子节点
            content.appendChild(elementDiv);
            //新增video元素
            var elementVideo = document.createElement('video');
            elementVideo.className = 'class_video';
            // elementVideo.controls = true;
            elementVideo.autoplay = true;
            elementVideo.src = info.att.videoUrl;
            // 为content添加img子节点
            content.appendChild(elementVideo);
          }
          /**
           * 动态设置元素文本内容（兼容）
           */
          function setInnerText(element, text) {
            if (typeof element.textContent == 'string') {
              element.textContent = text;
            } else {
              element.innerText = text;
            }
          }

          // 为map添加点击事件监听，渲染弹出popup
          _this.map.on('click', function (evt) {
            //判断当前单击处是否有要素，捕获到要素时弹出popup
            var feature = _this.map.forEachFeatureAtPixel(
              evt.pixel,
              function (feature, layer) {
                return feature;
              }
            );
            if (feature) {
              var obj = feature.values_.values_;
              //示例标注点的信息对象
              var featuerInfo = {
                geo: feature,
                att: {
                  //标注信息的标题内容
                  title: '摄像头编号：' + obj.编号,
                  //标注详细信息链接
                  titleURL: 'http://www.openlayers.org/',
                  //标注内容简介
                  text: '位置：' + obj.位置,
                  //标注的图片
                  videoUrl: '../../src/assets/视频.mp4',
                },
              };

              //清空popup的内容容器
              content.innerHTML = '';
              //在popup中加载当前要素的具体信息
              addFeatrueInfo(featuerInfo);
              if (popup.getPosition() == undefined) {
                //设置popup的位置, 此时还未打开过popup弹窗
                var position = feature.getGeometry().getCoordinates()[0];
                popup.setPosition(position);
              } else {
                // 如果feature的为新点击的对象, 则赋予popup新的显示位置
                var position = feature.getGeometry().getCoordinates()[0];
                popup.setPosition(position);
              }
            }
          });
          // 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
          _this.map.on('pointermove', function (e) {
            // console.log(e.originalEvent);
            var pixel = _this.map.getEventPixel(e.originalEvent);
            var hit = _this.map.hasFeatureAtPixel(pixel);
            _this.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
          });
          drawLayer.setVisible(true);
        } else {
          // 切换显示图层, 关闭高亮显示图层
          // console.log('摄像头关闭状态');
          drawLayer.setVisible(false);
          _this.map.removeLayer(drawLayer);
        }
      }
    },
  },
};
</script>

<style>
#map_container {
  position: absolute;
  width: 100vw;
  height: 100vh;
}
/* 放大缩小 */
.ol-zoom {
  top: 10em;
  left: 102em;
  /* background-color: red; */
}
.ol-overlaycontainer-stopevent .ol-scale-line {
  left: 23px;
  bottom: 10px;
}
.ol-control button {
  /* display: block; */
  margin: 1px;
  padding: 0;
  color: #646464;
  font-size: 1.3em;
  font-weight: 700;
  text-decoration: none;
  text-align: center;
  height: 1.375em;
  width: 1.375em;
  line-height: 0.4em;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 2px;
}
.ol-control button:focus,
.ol-control button:hover {
  text-decoration: none;
  background-color: #317fcd;
  color: white;
}
/* 复位控件 */
.ol-zoom-extent {
  top: 16em;
  left: 102em;
  background-color: rgb(255, 255, 255, 0.5);
}
/* 鹰眼样式 */
.ol-overviewmap:not(.ol-collapsed) {
  background: rgba(255, 255, 255, 0.8);
  position: absolute;
  left: 89%;
  bottom: 3%;
}
.ol-overviewmap {
  left: 1400px;
  bottom: 0.5em;
}
/* 地图切换 */
.changeMap {
  position: absolute;
  bottom: 340px;
  top: 310px;
  right: 20px;
  z-index: 10;
}

.el-tooltip__popper.is-dark {
  background: #317fcd;
  color: #fff;
}
.changeMap .change1 {
  margin-bottom: 8px;
}

.changeMap .change1,
.changeMap .change2 {
  height: 40px;
  width: 40px;
  display: flex;
  border-radius: 50%;
  margin-right: 15px;
  /* border: 0px solid #fff; */
  background-color: #fff;
}

/* 比例尺 */
.ol-scale-line {
  left: 200px;
  bottom: 10px;
}
button {
  z-index: 100;
}
/* popup弹窗 */
/* popup弹窗 */
.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 9px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 45px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: '✖';
}

#popup-content {
  padding-bottom: 10px;
  font-size: 14px;
  font-family: '微软雅黑';
}
.class_video {
  width: 280px;
}
.class_a {
  font-weight: 700;
  text-decoration: none;
  color: black;
}
</style>
